package dao

import (
	"fmt"
	"github.com/kataras/iris/core/errors"
	"github.com/patrickmn/go-cache"
	"gopkg.in/gomail.v2"
	"log"
	"strings"
	"time"
	"wow-web/config"
	"wow-web/models"
)

type mailDao struct {
	mailsCache *cache.Cache
}

func newMailDao() *mailDao {
	return &mailDao{mailsCache: cache.New(10*time.Minute, 10*time.Second)}
}

func (dao *mailDao) PreRegistration(mail *models.Mail) error {
	key := strings.ToLower(mail.Mail)
	if _, ok := dao.mailsCache.Get(key); ok {
		return errors.New("邮箱认证中，稍后再试")
	}
	dao.mailsCache.SetDefault(key, mail)
	go sendEmail(mail)
	return nil
}

func (dao *mailDao) GetMail(mail string) *models.Mail {
	key := strings.ToLower(mail)
	m, ok := dao.mailsCache.Get(key)
	if ok {
		return m.(*models.Mail)
	}
	return nil
}
func (dao *mailDao) DeleteMail(mail string) {
	key := strings.ToLower(mail)
	dao.mailsCache.Delete(key)
}

var mailTemplate = `账号: %s<br/>
认证链接: <a target="_blank" href="%s">%s</a>
`

func sendEmail(mail *models.Mail) {
	log.Println(fmt.Sprintf("send mail: %s<%s>, code: %s", mail.Username, mail.Mail, mail.Code))

	conf := config.GetConfig()

	m := gomail.NewMessage()
	m.SetAddressHeader("From", conf.Smtp.Mail, "GM")
	m.SetHeader("To", m.FormatAddress(mail.Mail, mail.Username))
	m.SetHeader("Subject", "注册邮箱认证邮件")
	m.SetBody("text/html", fmt.Sprintf(mailTemplate, mail.Username, mail.Url, mail.Url))

	d := gomail.NewDialer(conf.Smtp.Host, conf.Smtp.Port, conf.Smtp.User, conf.Smtp.Password)

	if err := d.DialAndSend(m); err != nil {
		log.Println(err)
	}
}
